<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\models\user\EmailToken;
use App\other\TokenType;
use App\other\UtilsClass;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Mail;
use Validator;

class ResetPasswordController extends Controller
{
    public function __construct(){
        $this->middleware('guest');
    }

    public function passwdReset(){
        return view('auth.passwdReset');
    }

    public function sendResetEmal(Request $request){
        $validator = Validator::make($request->all(), [
            'email'     => 'required|email|exists:users,email',
        ]);

        if ($validator->fails()){
            return redirect('/password/reset')->with(['_error' => '邮箱不存在']);
        }
        $this->sendPasswdReselEamil($request->get('email'));
        return redirect('/password/reset')->with(['status' => '密码重置邮件已经发送至你的邮箱']);
    }

    protected function sendPasswdReselEamil($email){
        $user               = User::where('email', $email)->first();
        EmailToken::deleteToken($user->id, TokenType::TOKEN_PASSWDRESET_TYPE);
        $token              = new EmailToken();
        $token->uid         = $user->id;
        $token->type        = TokenType::TOKEN_PASSWDRESET_TYPE;
        $token->token       = UtilsClass::getRandomStringCode(32);
        $token->dead_time   = time()+60*60;
        $token->save();
        $data = [
            'email' => $user->email,
            'name'=>env('MAIL_NAME', 'MeShop'),
            'token'=>$token->token ,
            'id'=>$token->id, 'username'=>$user->name
        ];
        Mail::send('mail.password', $data, function(Message $message) use($data) {
            $message->to($data['email'], $data['username'])->subject('重置密码！');
        });
    }
}
